const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        address: {},
        isAddr: false, //暂无地址提示是否展示
        total: 0,
        post_style: '送货上门',
        proNums: 0, //共多少件商品
        couponDialogShow: false, //优惠券弹窗是否打开
        payDialogShow: false, //支付方式弹窗是否打开
        product: [],
        total: 0.00,
        ids: [],
        nums: [],
        userStoredNum: 0,  // 用户积分
        currTotal: 0,// 使用积分金额
        realMoney: 0,// 实际支付金额
        isSpecialProduct: false,// 是否为特殊商品
        isEnough: false,// 积分是否够半价
        payWay: '1', // 1 使用积分支付 2 不使用积分支付
        user: '',

        parentId: 0,// 上级ID
        highestId: 0,// 上上级ID
        rebate: 0,//上级返利
        rebates: 0,//上上级返利

        myVipFlag: 0,// 我的会员身份  0 不是会员  1 是会员 
        parentVipFlag: 0, // 上级会员身份
        highestVipFlag: 0, // 上上级会员身份

    },

    //门店自提滑块点击时切换状态
    switchClick: function () {
        this.setData({
            switchOpen: !this.data.switchOpen
        })
    },

    //关闭支付方式弹窗
    closePayDialog: function () {
        this.setData({
            payDialogShow: false
        })
    },
    noCheck(e) {
        console.log(e);
        var flag = e.currentTarget.dataset.flag, total = this.data.total, currTotal = 0, realMoney = 0, isEnough = this.data.isEnough, userStoredNum = this.data.userStoredNum;

        if (flag == 1) {
            // 使用积分
            if (isEnough) {
                currTotal = total
                realMoney = 0
            } else {
                currTotal = userStoredNum
                realMoney = total - userStoredNum
            }

        } else {
            // 不使用积分
            currTotal = 0
            realMoney = total
        }

        this.setData({
            payWay: flag,
            currTotal,
            realMoney,
            couponDialogShow: false
        })
    },
    //关闭优惠券弹窗
    closeCouponDialog() {
        this.setData({
            couponDialogShow: false
        })
    },
    toOpen: function () {
        this.setData({
            couponDialogShow: true
        })
    },
    handleNote(e) {
        this.setData({
            note: e.detail.value
        })
    },
    toChooseAddress() {
        wx.navigateTo({
            url: '/packageUser/pages/address/address?flag=1',
        })
    },

    getUserData() {
        wx.showLoading({
            title: '加载中',
        })
        var that = this, productList = this.data.product, isEnough = false, payWay = 2, userStoredNum = 0, myVipFlag = 0, total = 0, currTotal = 0, realMoney = 0, proNums = 0, url = app.globalData.url + "points/listPoints",
            data = {
                userId: app.globalData.userId,
            }, isSpecialProduct = false;
        app.wxRequest(url, data, res => {
            console.log(res.data);
            if (res.flag) {
                wx.hideLoading()
                if (res.data != null) {
                    myVipFlag = res.data.note
                    userStoredNum = res.data.remainingTotalScore
                }
                productList.forEach(item => {
                    if (item.productFlag == 1) {
                        isSpecialProduct = true
                    }
                    total += item.productNum * item.formatPrice
                    proNums += item.productNum
                })
                realMoney = total
                if (userStoredNum > 0 && !isSpecialProduct) {
                    if (userStoredNum >= total) {
                        isEnough = true
                        currTotal = total
                        realMoney = 0
                        payWay = 1
                    } else {
                        currTotal = userStoredNum
                        realMoney = total - currTotal
                        payWay = 1
                    }
                }

                that.setData({
                    userStoredNum, total, proNums, realMoney, currTotal, isEnough, payWay, isSpecialProduct,
                    myVipFlag
                })
            }
        })
    },

    // 获取我的上级 上上级id
    getUserParentId() {
        wx.showLoading({
            title: '加载中',
        })
        var that = this, url = app.globalData.url + "user/listHigherUser",
            data = {
                userId: app.globalData.userId
            };
        app.wxRequest(url, data, res => {
            console.log(res.data);
            if (res.flag) {
                wx.hideLoading()
                that.setData({
                    parentId: res.data.pater != null ? res.data.pater.userId || 0 : 0,
                    parentVipFlag: res.data.pater != null ? res.data.pater.note || 0 : 0,
                    highestId: res.data.grandsire != null ? res.data.grandsire.userId || 0 : 0,
                    highestVipFlag: res.data.grandsire != null ? res.data.grandsire.note || 0 : 0
                })
                console.log(that.data);
            }
        })
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            product: JSON.parse(options.product),
            picPath: app.globalData.path,
        })
        console.log(this.data.product);
        this.getUserParentId()
        this.getUserData()
        this.getVipFlag()
    },
    //提交订单
    toSub() {
        var that = this, isSpecialProduct = this.data.isSpecialProduct;
        if (!this.data.isAddr) {
            wx.showToast({
                title: '请选择收货地址',
                icon: 'none'
            })
            return
        }

        wx.showModal({
            title: '提示',
            content: `是否${that.data.realMoney == 0 ? '使用积分' : ''}购买该商品`,
            complete: (res) => {
                if (res.cancel) {
                }
                if (res.confirm) {
                    wx.showLoading({
                        title: '',
                    })
                    var url = app.globalData.url + (isSpecialProduct ? 'order/addMiniOrder' : 'order/addMiniProductOrder'), obj = '', product = that.data.product;
                    console.log(url);
                    obj = {
                        userId: app.globalData.userId,
                        shopId: app.globalData.shopId,
                        userName: that.data.address.userName,
                        userTel: that.data.address.userTel,
                        userAddr: that.data.address.userAddr,
                        totalMoney: that.data.total,
                        realMoney: that.data.realMoney,
                        usedStored: that.data.realMoney,
                        payWay: that.data.payWay == 1 ? that.data.isEnough ? '积分支付' : '积分抵扣+微信支付' : '微信支付',
                        usedYh: that.data.currTotal,
                        parentId: that.data.parentId || 0,
                        orderList: [],
                    }
                    product.forEach(item => {
                        obj.orderList.push({
                            productId: item.productId,
                            formatId: item.formatId,
                            productPrice: item.formatPrice,
                            productNum: item.productNum,
                            productName: item.productName,
                            formatName: item.formatName,
                            formatImg: item.formatImg,
                            productFlag: item.productFlag,
                        })
                    })

                    if (isSpecialProduct) {
                        obj.highestId = that.data.highestId || 0
                    }
                    console.log(obj);
                    app.wxRequestJSON(url, obj, res => {
                        wx.hideLoading()
                        if (res.flag) {
                            if (that.data.realMoney == 0) {
                                wx.showModal({
                                    title: '提示',
                                    content: '已使用积分购买该商品',
                                    confirmText: '立即查看',
                                    complete: (res) => {
                                        if (res.cancel) {
                                            this.onLoad()
                                        }
                                        if (res.confirm) {
                                            wx.navigateTo({
                                                url: "/packageProduct/pages/orderList/orderList?index=1",
                                            })
                                        }
                                    }
                                })
                            } else {
                                var datas = res.data;
                                console.log(datas);
                                that.setData({
                                    rebate: datas.rebate,
                                    rebates: datas.rebates,
                                })

                                that.wxPay(datas.orderNum, that.data.realMoney);
                            }
                        } else {
                            wx.showToast({
                                title: '提交失败，请重试',
                                icon: 'none'
                            })
                        }
                    }, err => { });
                }
            }
        })
    },

    wxPay(order_num, sum) {
        console.log(order_num);
        console.log(sum);
        // return
        wx.showLoading({
            title: '',
        })
        var that = this, isSpecialProduct = this.data.isSpecialProduct, url = app.globalData.url + (isSpecialProduct ? 'pay/payMiniOrder' : 'pay/payMiniProductOrder'),
            data = {
                userId: app.globalData.userId,
                shopId: app.globalData.shopId,
                orderNumber: order_num,
                realMoney: sum,
                flag: 1,
                openId: app.globalData.openId,
                ifDown: 0,
            };
        if (isSpecialProduct) {
            data.highestId = that.data.highestId || 0
            data.parentId = that.data.parentId || 0
            data.rebate = that.data.rebate || 0
            data.rebates = that.data.rebates || 0
            // data.parentNote = that.data.parentVipFlag || 0
            // data.highestNote = that.data.highestVipFlag || 0
            data.note = that.data.myVipFlag || 0
        } else {
            data.usedYh = that.data.currTotal
        }
        app.wxRequest(url, data, res => {
            wx.hideLoading()
            if (res.flag) {
                console.log(res.data);
                console.log(res.data.finalPackage);
                that.realPay(res.data.finalPackage);
            } else {
                wx.showToast({
                    title: '提交失败，请重试',
                    icon: 'none'
                })
            }
        }, err => {

        })
    },


    realPay(datas) {
        var that = this;

        console.log(datas);
        wx.requestPayment({
            timeStamp: datas.timeStamp,
            nonceStr: datas.nonceStr,
            package: datas.package,
            signType: datas.signType,
            paySign: datas.paySign,
            success(res) {
                console.log(res);
                if (res.errMsg == "requestPayment:ok") {
                    if (that.data.isSpecialProduct) {
                        that.getVipFlag()
                    }
                    wx.showModal({
                        title: '提示',
                        content: '支付成功',
                        showCancel: false,
                        complete: (res) => {
                            if (res.confirm) {
                                wx.redirectTo({
                                    url: '/packageProduct/pages/orderList/orderList?index=1',
                                })
                            }
                        }
                    })
                }
            },
            fail(res) {
                wx.hideLoading()
                wx.showToast({
                    title: '支付失败',
                    icon: 'none'
                })

            }
        })
    },


    getVipFlag() {
        wx.showLoading({
            title: '加载中',
        })
        var url = app.globalData.url + "points/listLowerUser", that = this,
            data = {
                userId: app.globalData.userId,
            };
        app.wxRequest(url, data, res => {
            console.log(res.data);
            if (res.flag) {
                wx.hideLoading()
                if (res.data != null) {
                    that.setData({
                        myVipFlag: res.data.user.note
                    })
                }
            }
        })
    },





    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.setData({
            address: '',
            isAddr: false
        })
        if (wx.getStorageSync('address')) {
            var address = JSON.parse(wx.getStorageSync('address'))
            this.setData({
                address,
                isAddr: true
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})